package finance;

import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.write.*;
import jxl.write.Number;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Center812Stat {

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy");

    public static void main(String[] args) throws IOException, ParseException, WriteException {
        int page = 1;
        List<Item> items = new ArrayList<Item>();
        while (true) {
            Document doc = Jsoup.connect("http://zakazcenter812.ru/index.php?2&2&2&act=list&ok=addOrder&page=" + page++).
                    cookie("type", "shop").
                    cookie("shop_id", "7").
                    cookie("shop_name", "extra").
                    cookie("shop_pass", "d2c75a26973a1888f241125717b166cf").
                    get();
            Elements rows = doc.select("table.table tr");
            if (rows.size() < 1) {
                break;
            }
            int count = 0;
            for (Element row : rows) {
                if (count++ == 0) {
                    continue;
                }
                Elements columns = row.select("td");
                Item item = new Item();
                item.count = count;
                item.delivery = columns.get(1).text();
                item.order = columns.get(2).text();
                item.amount = new BigDecimal(Double.parseDouble(columns.get(3).text()));
                item.shop = columns.get(4).text();
                item.date = DATE_FORMAT.parse(columns.get(5).text());
                item.status = columns.get(7).text();
                items.add(item);
            }
        }
        Collections.sort(items, new Comparator<Item>() {
            public int compare(Item o1, Item o2) {
                return o1.date.compareTo(o2.date);
            }
        });


        int dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK_IN_MONTH);
        Date from = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000 * dayOfWeek);
        Date to = new Date();

        int weeks = 3;
        while (true) {
            if (weeks == 0) {
                break;
            }
            String fileName = DATE_FORMAT.format(from) + " - " + DATE_FORMAT.format(to);
            System.out.println(fileName);
            List<Item> filteredItems = new ArrayList<Item>();
            for (Item item : items) {
                if (!checkInInterval(from, to, item)) {
                    continue;
                }
                System.out.println(item);
                filteredItems.add(item);
            }
            saveToExcel(filteredItems, fileName);
            to = from;
            long twoWeeksBack = 24 * 60 * 60 * 1000 * 14;
            from = new Date(from.getTime() - twoWeeksBack);
            weeks--;
        }
    }

    private static boolean checkInInterval(Date from, Date to, Item item) {
        return item.date.before(to) && item.date.after(from);
    }

    private static void saveToExcel(List<Item> items, String fileName) throws IOException, WriteException {
        String file = "finance/" + fileName + ".xls";
        File xlsFile = new File(file);
        WorkbookSettings s = new WorkbookSettings();
        s.setLocale(new Locale("ru", "RU"));
        s.setEncoding("KOI8-R");
        WritableWorkbook workbook = Workbook.createWorkbook(xlsFile, s);

        workbook.createSheet("Финансы", 0);
        WritableSheet sheet = workbook.getSheet(0);

        addHeader(sheet);

        int rows = 0;
        BigDecimal totalAmount = new BigDecimal(0);
        BigDecimal totalPureAmount = new BigDecimal(0);
        BigDecimal totalDeliveryAmount = new BigDecimal(0);
        BigDecimal totalDeliveryPercent = new BigDecimal(0);
        BigDecimal totalPureDeliveryAmount = new BigDecimal(0);

        for (Item item : items) {
            BigDecimal amount = item.amount;
            BigDecimal deliveryPercent = item.amount.multiply(new BigDecimal(1.5)).divide(new BigDecimal(100.));
            BigDecimal deliveryCost = item.delivery.equals("Выдача") ? new BigDecimal(70) : new BigDecimal(220);
            if (item.status.equals("Выдан")) {
            } else if (item.status.equals("Нет на складе")) {
                amount = new BigDecimal(0);
                deliveryCost = new BigDecimal(0);
                deliveryPercent = new BigDecimal(0);
            } else if (item.status.equals("Клиент не пришёл") || item.status.equals("В работе") || item.status.equals("Отказ клиента")) {
                amount = new BigDecimal(0);
                deliveryPercent = new BigDecimal(0);
            } else {
                throw new IllegalArgumentException("Unknown item status: " + item);
            }
            BigDecimal pureAmount = amount.subtract(deliveryCost).subtract(deliveryPercent);
            BigDecimal pureDeliveryCost = deliveryCost.add(deliveryPercent);
            rows++;
            WritableCell cell = new DateTime(0, rows, item.date);
            sheet.addCell(cell);
            cell = new Label(1, rows, item.order);
            sheet.addCell(cell);
            cell = new Label(2, rows, item.status);
            sheet.addCell(cell);
            cell = new jxl.write.Number(3, rows, amount.doubleValue());
            sheet.addCell(cell);
            cell = new jxl.write.Number(4, rows, deliveryCost.doubleValue());
            sheet.addCell(cell);
            cell = new jxl.write.Number(5, rows, deliveryPercent.doubleValue());
            sheet.addCell(cell);
            cell = new jxl.write.Number(6, rows, pureDeliveryCost.doubleValue());
            sheet.addCell(cell);
            cell = new jxl.write.Number(7, rows, pureAmount.doubleValue());
            sheet.addCell(cell);

            totalAmount = totalAmount.add(amount);
            totalDeliveryAmount = totalDeliveryAmount.add(deliveryCost);
            totalDeliveryPercent = totalDeliveryPercent.add(deliveryPercent);
            totalPureAmount = totalPureAmount.add(pureAmount);
            totalPureDeliveryAmount = totalPureDeliveryAmount.add(pureDeliveryCost);
        }
        rows++;
        sheet.addCell(new Label(0, rows, "Итого:"));
        sheet.addCell(new Number(3, rows, totalAmount.doubleValue()));
        sheet.addCell(new Number(4, rows, totalDeliveryAmount.doubleValue()));
        sheet.addCell(new Number(5, rows, totalDeliveryPercent.doubleValue()));
        sheet.addCell(new Number(6, rows, totalPureDeliveryAmount.doubleValue()));
        sheet.addCell(new Number(7, rows, totalPureAmount.doubleValue()));

        workbook.write();
        workbook.close();
    }

    public static void addHeader(WritableSheet sheet) throws WriteException {
        WritableCell cell = new Label(0, 0, "Дата");
        sheet.addCell(cell);
        cell = new Label(1, 0, "Заказ");
        sheet.addCell(cell);
        cell = new Label(2, 0, "Статус");
        sheet.addCell(cell);
        cell = new Label(3, 0, "Сумма выдачи");
        sheet.addCell(cell);
        cell = new Label(4, 0, "Сумма выдачи (доставки)");
        sheet.addCell(cell);
        cell = new Label(5, 0, "Процент за КО");
        sheet.addCell(cell);
        cell = new Label(6, 0, "Центр812 заработал");
        sheet.addCell(cell);
        cell = new Label(7, 0, "Мы заработали");
        sheet.addCell(cell);
    }


    static class Item {
        int count;
        String order;
        String delivery;
        String shop;
        BigDecimal amount;
        Date date;
        String status;

        @Override
        public String toString() {
            return "Item{" +
                    "count=" + count +
                    ", order='" + order + '\'' +
                    ", delivery='" + delivery + '\'' +
                    ", shop='" + shop + '\'' +
                    ", amount=" + amount +
                    ", date=" + date +
                    ", status='" + status + '\'' +
                    '}';
        }
    }
}
